package mustang

import (
	"bytes"
	"image"
	"image/draw"
	"image/jpeg"
)

var (
	Rate = jpeg.DefaultQuality
	step = 20
)

func DecRate() {
	Rate -= step
	if Rate <= 0 {
		Rate = 1
	}
}

func IncRate() {
	Rate += step
	if Rate > 100 {
		Rate = 100
	}
}

func SetRate(rate int) {
	Rate = rate
}

func ImageCompress(img *image.Image) ([]byte, error) {
	var buffer bytes.Buffer
	rgb := image.NewRGBA((*img).Bounds())
	draw.FloydSteinberg.Draw(rgb, rgb.Bounds(), *img, image.ZP)
	err := jpeg.Encode(&buffer, rgb, &jpeg.Options{Rate})
	if err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

func ImageExtract(data []byte) (*image.Image, error) {
	img, _, err := image.Decode(bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	return &img, nil
}
